import 'dart:io';

import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/a_yyt/page/home_page.dart';
import 'package:ls_work/config/global_configs.dart';
import 'package:ls_work/init_page/provider/home_provider.dart';
import 'package:ls_work/a_message/page/message_page.dart';
import 'package:ls_work/message/message_config.dart';
import 'package:ls_work/res/resources.dart';
import 'package:ls_work/a_elder/page/elder_page.dart';
import 'package:ls_work/a_training/page/training_page.dart';
import 'package:ls_work/a_mine/page/my_page.dart';
import 'package:ls_work/ui/new_yyt_page.dart';
import 'package:ls_work/util/image_utils.dart';
import 'package:ls_work/util/toast.dart';
import 'package:ls_work/widgets/load_image.dart';
import 'package:provider/provider.dart';

import '../login/page/login_page.dart';
import '../service/sos_warning_service.dart';
import '../util/native_toast.dart';
import '../util/speak_text_service.dart';

bool hasAgreeRoot = false;
class InitPage extends StatefulWidget {
  @override
  _InitPageState createState() => _InitPageState();
}

class _InitPageState extends State<InitPage> {

  var _pageList;
  var _tabImages;
  var _appBarTitles = ['消息', '长者', '数字康养', '信息发布', '我的'];
  final _pageController = PageController(initialPage: 2);

  HomeProvider provider = HomeProvider();

  List<BottomNavigationBarItem> _list = [];

  @override
  void initState() {
    super.initState();
    // print('🍎 - InitPage');
    initData();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _preCacheImage();
      showFloatingWidget();

      // NativeUtils.checkRootOrJailbreak().then((value) {
      //   if (value&&!hasAgreeRoot) {
      //     showHasRootDialog(context);
      //   }
      //   print("value");
      // });
    });
    // if(Platform.isAndroid){
    //   SosWarningService.instance.startService();
    // }
    initSpeech();
  }

  Future<void> initSpeech() async {
    await SpeakTextService.initTts();
  }

  _preCacheImage(){
    /// 预先缓存剩余图片
    precacheImage(ImageUtils.getAssetImage("tabbar/t_message_s"), context);
    precacheImage(ImageUtils.getAssetImage("tabbar/t_elder_s"), context);
    precacheImage(ImageUtils.getAssetImage("tabbar/t_yyt_n"), context);
    precacheImage(ImageUtils.getAssetImage("tabbar/t_train_s"), context);
    precacheImage(ImageUtils.getAssetImage("tabbar/t_mine_s"), context);
  }
  
  void initData(){
    _pageList = [
      MallPage(),
      ElderPage(),
      // HomePage(),
      NewYytPage(),
      TraningPage(),
      MyPage(),
    ];

    _tabImages = [
      [
        const LoadAssetImage("tabbar/t_message_n"),
        const LoadAssetImage("tabbar/t_message_s"),
      ],
      [
        const LoadAssetImage("tabbar/t_elder_n"),
        const LoadAssetImage("tabbar/t_elder_s"),
      ],
      [
        const LoadAssetImage("tabbar/t_yyt_n"),
        const LoadAssetImage("tabbar/t_yyt_s"),
      ],
      [
        const LoadAssetImage("tabbar/t_train_n"),
        const LoadAssetImage("tabbar/t_train_s"),
      ],
      [
        const LoadAssetImage("tabbar/t_mine_n"),
        const LoadAssetImage("tabbar/t_mine_s"),
      ]
    ];

    _list = List.generate(5, (i){
      return BottomNavigationBarItem(
          icon: _tabImages[i][0],
          activeIcon: _tabImages[i][1],
          // title: Padding(
          //   padding: const EdgeInsets.only(top: 5.0),
          //   child: Text(_appBarTitles[i], key: Key(_appBarTitles[i]),),
          // )
        label: _appBarTitles[i],
      );
    });
  }

  DateTime?  _lastTime;
  
  Future<bool> _isExit(){
    if (_lastTime == null || DateTime.now().difference(_lastTime!) > Duration(milliseconds: 2500)) {
      _lastTime = DateTime.now();
      Toast.show("再次点击退出应用");
      return Future.value(false);
    } 
    Toast.cancelToast();
    return Future.value(true);
  }
  
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<HomeProvider>(
      create: (context) => provider,
      child: WillPopScope(
        onWillPop: _isExit,
        child: Scaffold(
          bottomNavigationBar: Consumer<HomeProvider>(
            builder: (_, provider, __){
              return BottomNavigationBar(
                backgroundColor: Colors.white,
                items: _list,
                type: BottomNavigationBarType.fixed,
                currentIndex: provider.value,
                elevation: 5.0,
                iconSize: 21.0,
                selectedFontSize: Dimens.font_sp10,
                unselectedFontSize: Dimens.font_sp10,
                selectedItemColor: Colours.app_main,
                unselectedItemColor: Colours.text_dark,
                onTap: (index){
                  _pageController.jumpToPage(index);
                },
              );
            },
          ),
          // 使用PageView的原因参看 https://zhuanlan.zhihu.com/p/58582876
          body: PageView(
            controller: _pageController,
            onPageChanged: _onPageChanged,
            children: _pageList,
            physics: NeverScrollableScrollPhysics(), // 禁止滑动
          )
        ),
      ),
    );
  }

  void _onPageChanged(int index) {
    provider.value = index;
    if(index==2){
      eventBus.fire(SendMessageEvent(MessageConfig.REFRESH_HOME_COUNT));
    }
  }

  OverlayEntry? _overlayEntry;

  void showFloatingWidget() {
    _overlayEntry = OverlayEntry(
      builder: (context) => Positioned(
        // top: MediaQuery.of(context).padding.top,
        bottom: 0,right: 15,
        child: Material(child: CommonText(GlobalConfigs.appVersion,textSize: 13,textColor: Colors.grey),color: Colors.transparent,),
      ),
    );

    // 将悬浮窗添加到应用的覆盖层
    Overlay.of(context)!.insert(_overlayEntry!);
  }

  void hideFloatingWidget() {
    // 移除悬浮窗
    _overlayEntry?.remove();
    _overlayEntry = null;
  }


  @override
  void dispose() {
    hideFloatingWidget();
    super.dispose();
  }
}
